package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.PageResult;
import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.dto.PetInformationDto;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Pet;
import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.PetMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.PetService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.vo.PetInformationVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 宠物信息管理
 */
@Slf4j
@RestController
@Tag(name = "宠物信息管理")
@RequestMapping("/pet")
public class PetInformationController {

    @Autowired
    private PetService petService;
    
    @Autowired
    private PetMapper petMapper;
    
    // ==================== 管理后台接口 ====================
    
    @Operation(summary = "管理员查询宠物列表（支持高级动态查询）")
    @GetMapping({"/admin/list", "/admin/pet/list"})  // 支持 /api/pet/admin/list 和 /api/admin/pet/list（绝对路径覆盖类路径）
    // @PreAuthorize("hasRole('ADMIN')")  // 如需启用权限，取消注释
    public PageResult<PetInformationVo> getAdminPetList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "宠物名称") @RequestParam(required = false) String petName,
            @Parameter(description = "分类ID") @RequestParam(required = false) String categoryIdStr,
            @Parameter(description = "品种") @RequestParam(required = false) String breed,
            @Parameter(description = "最小年龄(月)") @RequestParam(required = false) String minAgeStr,
            @Parameter(description = "最大年龄(月)") @RequestParam(required = false) String maxAgeStr,
            @Parameter(description = "性别") @RequestParam(required = false) String genderStr,
            @Parameter(description = "最低价格") @RequestParam(required = false) String minPriceStr,
            @Parameter(description = "最高价格") @RequestParam(required = false) String maxPriceStr,
            @Parameter(description = "宠物状态") @RequestParam(required = false) String petStatusStr,
            @Parameter(description = "健康状态") @RequestParam(required = false) String healthStatusStr,
            @Parameter(description = "疫苗状态") @RequestParam(required = false) String vaccinationStatusStr,
            @Parameter(description = "绝育状态") @RequestParam(required = false) String sterilizationStatusStr,
            @Parameter(description = "主人ID") @RequestParam(required = false) String ownerIdStr,
            @Parameter(description = "负责员工ID") @RequestParam(required = false) String employeeIdStr,
            @Parameter(description = "是否已删除") @RequestParam(required = false, defaultValue = "false") Boolean deleted,
            @Parameter(description = "创建开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "创建结束日期") @RequestParam(required = false) String endDate,
            @Parameter(description = "排序字段") @RequestParam(required = false) String orderBy,
            @Parameter(description = "排序方向") @RequestParam(required = false, defaultValue = "desc") String order
    ) {
        try {
            // 转换参数（处理空字符串）
            Long categoryId = parseLong(categoryIdStr);
            Integer minAge = parseInt(minAgeStr);
            Integer maxAge = parseInt(maxAgeStr);
            Integer gender = parseInt(genderStr);
            java.math.BigDecimal minPrice = parseBigDecimal(minPriceStr);
            java.math.BigDecimal maxPrice = parseBigDecimal(maxPriceStr);
            Integer petStatus = parseInt(petStatusStr);
            Integer healthStatus = parseInt(healthStatusStr);
            Integer vaccinationStatus = parseInt(vaccinationStatusStr);
            Integer sterilizationStatus = parseInt(sterilizationStatusStr);
            Long ownerId = parseLong(ownerIdStr);
            Long employeeId = parseLong(employeeIdStr);
            
            log.info("管理员查询宠物列表 - pageNum: {}, pageSize: {}, petName: {}, categoryId: {}", 
                     pageNum, pageSize, petName, categoryId);
            log.info("筛选条件 - 品种: {}, 价格: [{}-{}], 年龄: [{}-{}], 性别: {}, 状态: {}", 
                     breed, minPrice, maxPrice, minAge, maxAge, gender, petStatus);
            
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Pet> queryWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            
            // 1. 宠物名称模糊查询
            if (org.springframework.util.StringUtils.hasText(petName)) {
                queryWrapper.like(Pet::getPetName, petName);
            }
            
            // 2. 分类精确查询
            if (categoryId != null && categoryId > 0) {
                queryWrapper.eq(Pet::getCategoryId, categoryId);
            }
            
            // 3. 品种模糊查询
            if (org.springframework.util.StringUtils.hasText(breed)) {
                queryWrapper.like(Pet::getBreed, breed);
            }
            
            // 4. 年龄范围（忽略0值）
            if (minAge != null && minAge > 0) {
                queryWrapper.ge(Pet::getAge, minAge);
            }
            if (maxAge != null && maxAge > 0) {
                queryWrapper.le(Pet::getAge, maxAge);
            }
            
            // 5. 性别（忽略0值）
            if (gender != null && gender > 0) {
                queryWrapper.eq(Pet::getGender, gender);
            }
            
            // 6. 价格范围（忽略0值）
            if (minPrice != null && minPrice.compareTo(java.math.BigDecimal.ZERO) > 0) {
                queryWrapper.ge(Pet::getPrice, minPrice);
            }
            if (maxPrice != null && maxPrice.compareTo(java.math.BigDecimal.ZERO) > 0) {
                queryWrapper.le(Pet::getPrice, maxPrice);
            }
            
            // 7. 各种状态（忽略0值，0通常表示"全部"或"未指定"）
            if (petStatus != null && petStatus > 0) {
                queryWrapper.eq(Pet::getPetStatus, petStatus);
            }
            if (healthStatus != null && healthStatus > 0) {
                queryWrapper.eq(Pet::getHealthStatus, healthStatus);
            }
            if (vaccinationStatus != null && vaccinationStatus >= 0) {
                // 疫苗状态：0=未接种，1=已接种，所以0是有意义的
                queryWrapper.eq(Pet::getVaccinationStatus, vaccinationStatus);
            }
            if (sterilizationStatus != null && sterilizationStatus >= 0) {
                // 绝育状态：0=未绝育，1=已绝育，所以0是有意义的
                queryWrapper.eq(Pet::getSterilizationStatus, sterilizationStatus);
            }
            
            // 8. 主人和员工
            if (ownerId != null && ownerId > 0) {
                queryWrapper.eq(Pet::getOwnerId, ownerId);
            }
            if (employeeId != null && employeeId > 0) {
                queryWrapper.eq(Pet::getEmployeeId, employeeId);
            }
            
            // 9. 删除状态
            queryWrapper.eq(Pet::getDeleted, deleted);
            
            // 10. 日期范围
            if (org.springframework.util.StringUtils.hasText(startDate)) {
                queryWrapper.ge(Pet::getCreateTime, startDate + " 00:00:00");
            }
            if (org.springframework.util.StringUtils.hasText(endDate)) {
                queryWrapper.le(Pet::getCreateTime, endDate + " 23:59:59");
            }
            
            // 11. 排序
            if (org.springframework.util.StringUtils.hasText(orderBy)) {
                boolean isAsc = "asc".equalsIgnoreCase(order);
                switch (orderBy.toLowerCase()) {
                    case "price":
                        queryWrapper.orderBy(true, isAsc, Pet::getPrice);
                        break;
                    case "age":
                        queryWrapper.orderBy(true, isAsc, Pet::getAge);
                        break;
                    case "createtime":
                        queryWrapper.orderBy(true, isAsc, Pet::getCreateTime);
                        break;
                    default:
                        queryWrapper.orderByDesc(Pet::getId);
                }
            } else {
                queryWrapper.orderByDesc(Pet::getId);
            }
            
            // 分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Pet> page = 
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Pet> result = 
                    petMapper.selectPage(page, queryWrapper);
            
            log.info("管理员查询结果 - 总记录数: {}, 当前页: {}, 总页数: {}", 
                     result.getTotal(), result.getCurrent(), result.getPages());
            
            // 转换为VO
            java.util.List<PetInformationVo> voList = result.getRecords().stream()
                    .map(this::convertToVO)
                    .collect(java.util.stream.Collectors.toList());
            
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<PetInformationVo> voPage = 
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(result.getCurrent(), result.getSize(), result.getTotal());
            voPage.setRecords(voList);
            
            return PageResult.success(voPage);
        } catch (Exception e) {
            log.error("管理员查询宠物列表失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }
    
    // ==================== 用户端接口 ====================

    /**
     * 分页动态查询宠物信息
     * @param pageNO
     * @param pageSize
     * @param petName
     * @param petType
     * @param gender
     * @return
     */
    @Operation(summary = "分页动态查询宠物信息")
    @PostMapping("/getPage")
    public PageResult<PetInformationVo> GetPetInformation(
            @RequestParam(name = "pageNO",defaultValue = "1") Integer pageNO,
            @RequestParam(name = "pageSize",defaultValue = "10") Integer pageSize,
            @RequestParam(name = "petName",required = false) String petName,
            @RequestParam(name = "petType",required = false) String petType,
            @RequestParam(name = "gender",required = false) Integer gender) {
        log.info("收到分页查询请求，查询宠物信息表");
        try {

            // 调用 Service 层进行分页查询
            IPage<PetInformationVo> page = petService.getPetsByCondition(pageNO, pageSize, petName, petType, gender);
            return PageResult.success(page);

        } catch (Exception e) {
            log.error(e.getMessage());
            return PageResult.pageError("查询失败："+e.getMessage());
        }
    }

    /**
     * 修改宠物信息
     * @param petInformationDto
     * @return
     */
    @Operation(summary = "修改宠物信息")
    @PostMapping("/updatePet")
    public Result UpdatePetInformation(@RequestBody PetInformationDto petInformationDto){
        log.info("接收到请求，修改宠物信息");
        try {
            petService.UpdatePetInformation(petInformationDto);
            return Result.success();
        }catch (Exception e){
            log.error(e.getMessage());
            return Result.error();
        }
    }

    @Operation(summary = "更新宠物信息（RESTful风格）")
    @PutMapping("/update/{id}")
    public Result updatePetById(
            @Parameter(description = "宠物ID") @PathVariable Long id,
            @RequestBody PetInformationDto petInformationDto) {
        log.info("更新宠物信息 - id: {}", id);
        try {
            // 确保DTO中的ID与路径参数一致
            petInformationDto.setId(id);
            petService.UpdatePetInformation(petInformationDto);
            return Result.success("更新成功");
        } catch (Exception e) {
            log.error("更新宠物信息失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除宠物信息
     * @param ids
     * @return
     */
    @Operation(summary = "批量删除宠物信息")
    @DeleteMapping("/deletePet")
    public Result DeletePetBatchInformation(@RequestBody List<Long> ids){
        return petService.deletePetBatch(ids) ? Result.success("批量删除成功") : Result.error("批量删除失败");
    }

    @Operation(summary = "获取宠物详情（通过ID）")
    @GetMapping("/{id}")
    public Result<PetInformationVo> getPetById(@Parameter(description = "宠物ID") @PathVariable Long id) {
        try {
            log.info("获取宠物详情 - id: {}", id);
            PetInformationVo pet = petService.getPetById(id);
            if (pet != null) {
                return Result.success(pet);
            }
            return Result.error("宠物不存在");
        } catch (Exception e) {
            log.error("获取宠物详情失败", e);
            return Result.error("获取详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除单个宠物")
    @DeleteMapping("/{id}")
    public Result deletePet(@Parameter(description = "宠物ID") @PathVariable Long id) {
        try {
            boolean success = petService.deletePetById(id);
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 创建宠物信息
     * @param petInformationDto
     * @return
     */
    @Operation(summary = "创建宠物信息")
    @PostMapping({"/add", "/create"})
    public Result createPet(@RequestBody PetInformationDto petInformationDto){
        return petService.createPet(petInformationDto) ? Result.success("新增宠物成功") : Result.error("新增宠物失败");
    }

    @Operation(summary = "获取宠物列表（支持多条件动态查询）")
    @GetMapping("/list")
    public PageResult<PetInformationVo> getPetList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "分类ID（精确查询，1=狗，2=猫，3=兔子，4=其他）") @RequestParam(required = false) Long categoryId,
            @Parameter(description = "分类名称/关键词（模糊查询，支持中英文）") @RequestParam(required = false) String category,
            @Parameter(description = "关键词（搜索宠物名称或品种）") @RequestParam(required = false) String keyword,
            @Parameter(description = "品种（模糊查询）") @RequestParam(required = false) String breed,
            @Parameter(description = "最低价格") @RequestParam(required = false) java.math.BigDecimal minPrice,
            @Parameter(description = "最高价格") @RequestParam(required = false) java.math.BigDecimal maxPrice,
            @Parameter(description = "最小年龄（月）") @RequestParam(required = false) Integer minAge,
            @Parameter(description = "最大年龄（月）") @RequestParam(required = false) Integer maxAge,
            @Parameter(description = "性别（1=公，2=母）") @RequestParam(required = false) Integer gender,
            @Parameter(description = "宠物状态（1=待售，2=已售，3=已被领养，4=已预定）") @RequestParam(required = false) Integer petStatus) {
        try {
            log.info("获取宠物列表 - pageNum: {}, pageSize: {}, categoryId: {}, category: {}, keyword: {}, breed: {}", 
                    pageNum, pageSize, categoryId, category, keyword, breed);
            log.info("价格范围: [{} - {}], 年龄范围: [{} - {}], gender: {}, petStatus: {}", 
                    minPrice, maxPrice, minAge, maxAge, gender, petStatus);
            
            // 构建查询条件（使用Lambda查询）
            com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Pet> queryWrapper = 
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
            
            // 1. 分类查询（优先使用 categoryId 精确查询）
            if (categoryId != null) {
                queryWrapper.eq(Pet::getCategoryId, categoryId);
                log.info("使用 categoryId 精确查询: {}", categoryId);
            } else if (org.springframework.util.StringUtils.hasText(category)) {
                // 使用 category 进行模糊查询（支持中英文）
                String categoryKeyword = mapCategoryKeyword(category);
                queryWrapper.and(wrapper -> 
                    wrapper.like(Pet::getBreed, categoryKeyword)
                           .or()
                           .like(Pet::getPetName, categoryKeyword)
                );
                log.info("使用 category 模糊查询: {} -> {}", category, categoryKeyword);
            }
            
            // 2. 关键词搜索（宠物名称或品种）
            if (org.springframework.util.StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> 
                    wrapper.like(Pet::getPetName, keyword)
                           .or()
                           .like(Pet::getBreed, keyword)
                );
                log.info("关键词搜索: {}", keyword);
            }
            
            // 3. 品种筛选
            if (org.springframework.util.StringUtils.hasText(breed)) {
                queryWrapper.like(Pet::getBreed, breed);
                log.info("品种筛选: {}", breed);
            }
            
            // 4. 价格范围
            if (minPrice != null) {
                queryWrapper.ge(Pet::getPrice, minPrice);
            }
            if (maxPrice != null) {
                queryWrapper.le(Pet::getPrice, maxPrice);
            }
            
            // 5. 年龄范围
            if (minAge != null) {
                queryWrapper.ge(Pet::getAge, minAge);
            }
            if (maxAge != null) {
                queryWrapper.le(Pet::getAge, maxAge);
            }
            
            // 6. 性别筛选
            if (gender != null) {
                queryWrapper.eq(Pet::getGender, gender);
            }
            
            // 7. 状态筛选（默认只查询待售和已预定的）
            if (petStatus != null) {
                queryWrapper.eq(Pet::getPetStatus, petStatus);
            } else {
                queryWrapper.in(Pet::getPetStatus, java.util.Arrays.asList(1, 4)); // 待售和已预定
            }
            
            // 8. 排序
            queryWrapper.orderByDesc(Pet::getCreateTime);
            
            // 分页查询
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Pet> page = 
                    new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNum, pageSize);
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<Pet> result = 
                    petMapper.selectPage(page, queryWrapper);
            
            log.info("查询结果 - 总记录数: {}, 当前页: {}, 每页数量: {}, 总页数: {}", 
                     result.getTotal(), result.getCurrent(), result.getSize(), result.getPages());
            
            // 转换为VO
            java.util.List<PetInformationVo> petVOList = result.getRecords().stream()
                    .map(this::convertToVO)
                    .collect(java.util.stream.Collectors.toList());
            
            // 构建PageResult
            IPage<PetInformationVo> pageResult = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                    result.getCurrent(), result.getSize(), result.getTotal());
            pageResult.setRecords(petVOList);
            
            return PageResult.success(pageResult);
        } catch (Exception e) {
            log.error("查询宠物列表失败", e);
            return PageResult.pageError("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 映射前端分类关键词
     * 支持中英文，大小写不敏感
     */
    private String mapCategoryKeyword(String category) {
        if (category == null) return "";
        String lower = category.toLowerCase();
        
        // 狗
        if (lower.matches(".*dog.*|.*狗.*")) {
            return "狗";
        }
        // 猫
        if (lower.matches(".*cat.*|.*猫.*")) {
            return "猫";
        }
        // 兔子
        if (lower.matches(".*rabbit.*|.*兔.*")) {
            return "兔";
        }
        // 仓鼠
        if (lower.matches(".*hamster.*|.*仓鼠.*")) {
            return "仓鼠";
        }
        // 鸟类
        if (lower.matches(".*bird.*|.*鸟.*")) {
            return "鸟";
        }
        // 其他
        if (lower.matches(".*other.*|.*其他.*")) {
            return "其他";
        }
        
        // 如果不匹配预定义，直接返回原值
        return category;
    }
    
    /**
     * 转换为VO对象
     */
    private PetInformationVo convertToVO(Pet pet) {
        PetInformationVo vo = new PetInformationVo();
        vo.setId(pet.getId());
        vo.setPetName(pet.getPetName());
        vo.setCategoryId(pet.getCategoryId());
        vo.setBreed(pet.getBreed());
        vo.setAge(pet.getAge());
        
        // 性别文本（PetInformationVo只有genderText字段）
        vo.setGenderText(pet.getGender() == 1 ? "公" : pet.getGender() == 2 ? "母" : "未知");
        
        vo.setPrice(pet.getPrice());
        vo.setOriginalPrice(pet.getOriginalPrice());
        
        // 图片字段（兼容）
        vo.setImageUrl(pet.getMainImage());
        vo.setMainImage(pet.getMainImage());
        vo.setImages(pet.getImages());
        
        // 状态字段
        vo.setPetStatus(pet.getPetStatus());
        vo.setPetStatusText(getPetStatusText(pet.getPetStatus()));
        
        // 健康状态文本
        vo.setHealthStatusText(getHealthStatusText(pet.getHealthStatus()));
        
        // 疫苗接种状态文本
        vo.setVaccinationStatusText(pet.getVaccinationStatus() != null && pet.getVaccinationStatus() == 1 ? "已接种" : "未接种");
        
        // 绝育状态文本
        vo.setSterilizationStatusText(pet.getSterilizationStatus() != null && pet.getSterilizationStatus() == 1 ? "已绝育" : "未绝育");
        
        vo.setDescription(pet.getDescription());
        vo.setOwnerId(pet.getOwnerId());
        vo.setEmployeeId(pet.getEmployeeId());
        vo.setViewCount(pet.getViewCount());
        vo.setLikeCount(pet.getLikeCount());
        vo.setCreateTime(pet.getCreateTime());
        vo.setUpdateTime(pet.getUpdateTime());
        
        return vo;
    }
    
    private String getPetStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 1: return "待售";
            case 2: return "已售";
            case 3: return "已被领养";
            case 4: return "已预定";
            default: return "未知";
        }
    }
    
    private String getHealthStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 1: return "健康";
            case 2: return "一般";
            case 3: return "需要关注";
            default: return "未知";
        }
    }
    
    /**
     * 解析Long类型参数（处理空字符串）
     */
    private Long parseLong(String value) {
        if (value == null || value.trim().isEmpty() || "null".equalsIgnoreCase(value) || "undefined".equalsIgnoreCase(value)) {
            return null;
        }
        try {
            return Long.parseLong(value.trim());
        } catch (NumberFormatException e) {
            log.warn("解析Long参数失败: {}", value);
            return null;
        }
    }
    
    /**
     * 解析Integer类型参数（处理空字符串）
     * 支持：null, "", "null", "undefined" -> null
     * 支持：数字字符串 -> Integer
     */
    private Integer parseInt(String value) {
        if (value == null || value.trim().isEmpty() || "null".equalsIgnoreCase(value) || "undefined".equalsIgnoreCase(value)) {
            return null;
        }
        try {
            String trimmed = value.trim();
            // 如果只是空格或空字符串，返回null
            if (trimmed.isEmpty()) {
                return null;
            }
            return Integer.parseInt(trimmed);
        } catch (NumberFormatException e) {
            log.warn("解析Integer参数失败: {}, 返回null", value);
            return null;
        }
    }
    
    /**
     * 解析BigDecimal类型参数（处理空字符串）
     * 支持：null, "", "null", "undefined" -> null
     * 支持：数字字符串 -> BigDecimal
     */
    private java.math.BigDecimal parseBigDecimal(String value) {
        if (value == null || value.trim().isEmpty() || "null".equalsIgnoreCase(value) || "undefined".equalsIgnoreCase(value)) {
            return null;
        }
        try {
            String trimmed = value.trim();
            // 如果只是空格或空字符串，返回null
            if (trimmed.isEmpty()) {
                return null;
            }
            return new java.math.BigDecimal(trimmed);
        } catch (NumberFormatException e) {
            log.warn("解析BigDecimal参数失败: {}, 返回null", value);
            return null;
        }
    }

    @Operation(summary = "获取单个宠物的详细信息")
    @GetMapping("/detail/{id}")
    public Result<PetInformationVo> getPetDetail(@Parameter(description = "宠物ID") @PathVariable Long id) {
        try {
            log.info("获取宠物详情 - id: {}", id);
            PetInformationVo pet = petService.getPetById(id);
            if (pet != null) {
                return Result.success(pet);
            }
            return Result.error("宠物不存在");
        } catch (Exception e) {
            log.error("获取宠物详情失败", e);
            return Result.error("获取详情失败: " + e.getMessage());
        }
    }

    @Operation(summary = "更新宠物状态（如在售、已售、寄养中）")
    @PutMapping("/status/{id}")
    public Result<?> updatePetStatus(
            @Parameter(description = "宠物ID") @PathVariable Long id,
            @Parameter(description = "宠物状态") @RequestParam Integer status) {
        try {
            PetInformationDto dto = new PetInformationDto();
            dto.setId(id);
            dto.setPetStatus(status);
            petService.UpdatePetInformation(dto);
            return Result.success("更新状态成功");
        } catch (Exception e) {
            log.error("更新宠物状态失败", e);
            return Result.error("更新状态失败: " + e.getMessage());
        }
    }
}
